const CACHE_NAME = 'iptv-player-cache-v1.0.1'; // 每次更新文件后，可以修改版本号来强制更新缓存

// 应用核心文件，也叫 "App Shell"
const urlsToCache = [
  '/',
  '/index.html',
  '/style.css',
  '/app.js',
  '/images/icon192.png'
];

// 安装 Service Worker，并缓存 App Shell
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        console.log('Opened cache and caching App Shell');
        return cache.addAll(urlsToCache);
      })
  );
});

// 拦截网络请求，实现 "缓存优先" 策略
self.addEventListener('fetch', event => {
  // 我们只对GET请求进行缓存
  if (event.request.method !== 'GET') {
    return;
  }
  
  // 对于CDN资源和API请求，我们采用网络优先策略，因为它们可能会更新
  const isExternalResource = event.request.url.includes('cdn.') || 
                               event.request.url.includes('cloudflare') || 
                               event.request.url.includes('unpkg') ||
                               event.request.url.includes('googleapis') ||
                               event.request.url.includes('vercel.app');

  if (isExternalResource) {
    // 网络优先，失败则回退到缓存
    event.respondWith(
      fetch(event.request)
        .catch(() => caches.match(event.request))
    );
  } else {
    // 本地资源，缓存优先
    event.respondWith(
      caches.match(event.request)
        .then(response => {
          return response || fetch(event.request);
        })
    );
  }
});

// 激活 Service Worker，并清理旧缓存
self.addEventListener('activate', event => {
  const cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheWhitelist.indexOf(cacheName) === -1) {
            console.log('Deleting old cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});